package org.colin.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.colin.Tools.ExportUtil;
import org.colin.Tools.FileUtil;
import org.colin.Tools.MD5Util;
import org.colin.Tools.RedisUtil;
import org.colin.Tools.TokenUtil;
import org.colin.Tools.Tool;
import org.colin.constant.Constants;
import org.colin.ds.DataSource;
import org.colin.mapper.SysResourceMapper;
import org.colin.mapper.SysRoleMapper;
import org.colin.mapper.SysUserMapper;
import org.colin.model.entity.SysUser;
import org.colin.model.ro.LoginRO;
import org.colin.model.ro.UserRoleRO;
import org.colin.model.vo.CustVO;
import org.colin.model.vo.Result;
import org.colin.model.vo.SysResourceVO;
import org.colin.model.vo.SysRoleVO;
import org.colin.model.vo.UserVO;
import org.colin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;

@Service
public class UserServiceImpl implements UserService {

    @Value("${system.tokenTimeout}")
    private Integer tokenTimeout;

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysResourceMapper sysResourceMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public Result insert(SysUser user) {
        String userId = Tool.getPrimaryKey();
        user.setId(userId);// 设置主键ID
        user.setLoginPass(MD5Util.md5(user.getLoginPass()));// 密码加密
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setUpdateUserId(tokenUtil.getRedisUser().getId());
        int result = sysUserMapper.insert(user);
        if (!Tool.isBlank(user.getRoleId())) {
            // 新增用户角色关联信息
            UserRoleRO userRoleRO = new UserRoleRO();
            userRoleRO.setUserId(userId);
            userRoleRO.setRoleId(user.getRoleId());
            sysUserMapper.addUserRole(userRoleRO);
        }
        if (result == 1) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }

    @Override
    public Result delete(String id) {
        int result = sysUserMapper.deleteByPrimaryKey(id);
        if (result == 1) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }

    @Override
    public Result selectAll(SysUser user) {
        List<UserVO> list = sysUserMapper.selectAll(user);
        int count = sysUserMapper.selectAllCount(user);
        return Result.success(list, count, user);
    }

    @DataSource(name = "second") // 指定连接的数据源
    @Override
    public void selectAllCust(HttpServletResponse httpServletResponse) {
        List<CustVO> custList = sysUserMapper.selectAllCust();
        if (custList != null && !custList.isEmpty()) {
            for (int i = 0; i < custList.size(); i++) {
                CustVO cust = custList.get(i);
                String idNo = cust.getCustIdNumber();// 获取身份证号
                Map<String, String> map = Tool.getInfoByIdCard(idNo);
                cust.setAge(Integer.valueOf(map.get("age")));
                cust.setCustSex(map.get("sex"));
                cust.setBirthday(map.get("birthday"));
                cust.setProvince(map.get("province"));
            }
        }
        // 开始下载
        Map<String, Object> exportMap = new HashMap<>();
        TemplateExportParams params = fileUtil.getTemplateExportParams("Cust.xls");
        exportMap.put("listMap", custList);
        Workbook workBook = ExcelExportUtil.exportExcel(params, exportMap);
        ExportUtil.exportExcel("Cust", workBook, httpServletResponse);
    }

    @Override
    public Result update(SysUser user) {
        user.setLoginPass(MD5Util.md5(user.getLoginPass()));// 密码加密
        user.setUpdateUserId(tokenUtil.getRedisUser().getId());
        if (!Tool.isBlank(user.getRoleId())) {
            // 新增用户角色关联信息
            UserRoleRO userRoleRO = new UserRoleRO();
            userRoleRO.setUserId(user.getId());
            userRoleRO.setRoleId(user.getRoleId());
            sysUserMapper.updateUserRole(userRoleRO);
        }
        int result = sysUserMapper.updateByPrimaryKeySelective(user);
        if (result == 1) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }

    // 系统登录
    @Override
    public UserVO login(LoginRO loginRO) {
        // 查询登录账号是否存在
        UserVO resultUser = sysUserMapper.selectByLoginName(loginRO.getLoginName());
        return resultUser;
    }

    // 系统注销
    @Override
    public Result loginOut() {
        // 获取请求头中的token参数值
        String token = tokenUtil.getToken();
        String tokenKey = Constants.TOKEN_KEY_STRING + token;
        redisUtil.expire(tokenKey, 1, "5");
        return Result.success();
    }

    // 强制某用户下线
    @Override
    public Result forceLoginOut(String userId) {
        redisUtil.expire(userId, 1, "5");
        return Result.success();
    }

}
